<template>
  <Dialog title="选择文件" @handle-confirm="handleConfirm">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <el-form-item label="原始文件" prop="origin">
        <div>
          <el-button @click="handleCheck('origin')">选择源文件</el-button>
        </div>
        <p class="fileName">{{ form.origin?.name }}</p>
      </el-form-item>
      <el-form-item label="标注结果" prop="new">
        <div>
          <el-button @click="handleCheck('new')">选择标注结果</el-button>
        </div>
        <p class="fileName">{{ form.new?.name }}</p>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import Dialog from "@/components/Dialog/index.vue";
import { ref } from "vue";
import { useFileDialog } from "@vueuse/core";
import { IContext, IJsonDataContext, IJsonItem } from "@/types/question";

interface EmitsType {
  (
    e: "success",
    value: {
      originJson: IJsonDataContext[];
      newJson: IJsonDataContext[];
    }
  );
}

const emit = defineEmits<EmitsType>();

const formRef = ref();
const form = ref<{
  origin: File | null;
  new: File | null;
}>({
  origin: null,
  new: null,
});

const rules = ref({
  origin: [{ required: true, message: "请选择源文件", trigger: "change" }],
  new: [{ required: true, message: "请选择结果文件", trigger: "change" }],
});

const { files, open, reset, onChange } = useFileDialog({
  accept: ".json", // Set to accept only image files
});

onChange((e) => {
  if (!files.value) return;
  if (currentType.value === "origin") {
    form.value.origin = files.value[0];
  } else {
    form.value.new = files.value[0];
  }
});

type FileType = "origin" | "new";
const currentType = ref<FileType>("origin");
const handleCheck = (type: "origin" | "new") => {
  currentType.value = type;
  open();
};

const isJSON = (str: string) => {
  if (typeof str !== "string") {
    return false;
  }

  try {
    const obj = JSON.parse(str);
    if (typeof obj === "object" && obj) {
      return true;
    } else {
      return false;
    }
  } catch (e) {
    return false;
  }
};

const readFile = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function () {
      resolve(reader.result);
    };
    reader.onerror = function () {
      reject(new Error("Failed to read file"));
    };
    reader.readAsText(file, "UTF-8");
  });
};
const handleConfirm = async () => {
  await formRef.value.validate();
  let originText, newText;
  try {
    originText = await readFile(form.value.origin!);
    newText = await readFile(form.value.new!);
    if (isJSON(originText) && isJSON(newText)) {
      const originContent: IJsonItem[] = JSON.parse(originText);
      const newContent: IJsonItem[] = JSON.parse(newText);
      const originContexts: IContext[] = [];
      const newContexts: IContext[] = [];
      originContent.forEach((content) => {
        if (
          !originContexts.find(
            (e) => e.context_id === content.context.context_id
          )
        ) {
          originContexts.push(content.context);
        }
      });

      newContent.forEach((content) => {
        if (
          !newContexts.find((e) => e.context_id === content.context.context_id)
        ) {
          newContexts.push(content.context);
        }
      });

      const originJson: IJsonDataContext[] = originContexts.map((item) => {
        return {
          context_id: item.context_id,
          context: item.context,
          qaList: originContent
            .filter((e) => e.context.context_id === item.context_id)
            .map((e) => {
              return {
                question: e.question,
                answer: e.answer,
                question_type: e.question_type,
              };
            }),
        };
      });
      const newJson: IJsonDataContext[] = newContexts.map((item) => {
        return {
          context_id: item.context_id,
          context: item.context,
          qaList: newContent
            .filter((e) => e.context.context_id === item.context_id)
            .map((e) => {
              return {
                question: e.question,
                answer: e.answer,
                question_type: e.question_type,
              };
            }),
        };
      });
      console.log(originJson, newJson);
      emit("success", {
        originJson,
        newJson,
      });
      // fileSelectRef.value!.value = "";
    }
  } catch (error) {}
};
</script>

<style scoped lang="scss">
.fileName {
  font-size: 16px;
  margin-left: 10px;
}
</style>
